package hos.base.dialog;

import android.app.Dialog;
import android.os.Bundle;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.fragment.app.DialogFragment;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;

import hos.base.activity.BaseActivity;
import hos.base.view.IFragmentActivityX;
import hos.thread.IThread;

public class AlertDialogFragment extends DialogFragment implements IFragmentActivityX<BaseActivity>, IThread {
    protected AlertDialog.Builder builder;

    public static AlertDialogFragment showDialog(@NonNull AlertDialog.Builder builder) {
        AlertDialogFragment alertDialogFragment = new AlertDialogFragment(builder);
        alertDialogFragment.show();
        return alertDialogFragment;
    }

    public AlertDialogFragment(@NonNull AlertDialog.Builder builder) {
        this.builder = builder;
    }

    @NonNull
    @Override
    public Dialog onCreateDialog(@Nullable Bundle savedInstanceState) {
        return builder.create();
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        onViewShowed(view);
    }

    public void show() {
        show(getClass().getSimpleName());
    }

    public void show(final String tag) {
        postOnMain(new Runnable() {
            @Override
            public void run() {
                FragmentManager fm = activity().getSupportFragmentManager();
                Fragment prev = fm.findFragmentByTag(tag);
                if (prev != null) {
                    fm.beginTransaction().remove(prev);
                }
                AlertDialogFragment.super.show(fm, tag);
            }
        });
    }

    public void showNow() {
        showNow(getClass().getSimpleName());
    }

    public void showNow(@Nullable String tag) {
        postOnMain(new Runnable() {
            @Override
            public void run() {
                FragmentManager fm = activity().getSupportFragmentManager();
                Fragment prev = fm.findFragmentByTag(tag);
                if (prev != null) {
                    fm.beginTransaction().remove(prev);
                }
                AlertDialogFragment.super.showNow(fm, tag);
            }
        });
    }

    @Override
    public void dismiss() {
        postOnMain(new Runnable() {
            @Override
            public void run() {
                AlertDialogFragment.super.dismissAllowingStateLoss();
            }
        });
    }

    @Override
    public void onViewShowed(View view) {

    }
}


